package org.hako.recite.word.tool;

import java.io.IOException;

import org.hako.recite.word.parser.WordList;
import org.hako.recite.word.parser.WordListParseException;
import org.hako.recite.word.parser.WordListParser;
import org.hako.recite.word.parser.factory.WordListParserFactory;
import org.hako.recite.word.parser.impl.UnsupportedFileExtensionException;
import org.hako.recite.word.tool.writer.DataFileWordListWriter;
import org.hako.recite.word.tool.writer.TextFileWordListWriter;
import org.hako.recite.word.tool.writer.WordListFileWriter;
import org.hako.recite.word.tool.writer.WordListWriteException;

/**
 * Convert word list file from xls/ods/txt/dat to txt/dat.
 * 
 * @since 0.4.9
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class ConvertWordListFileFormat {

	/**
	 * Main.
	 * 
	 * @param args
	 * @throws UnsupportedFileExtensionException
	 * @throws WordListParseException
	 * @throws IOException
	 * @throws WordListWriteException
	 */
	public static void main(String[] args)
			throws UnsupportedFileExtensionException, WordListParseException,
			IOException, WordListWriteException {
		int argumentCount = args.length;
		if (argumentCount < 1) {
			showUsage();
			return;
		}
		String filePath = args[0];
		WordListParserFactory parserFactory = new WordListParserFactory();
		WordListParser parser = parserFactory.getParser(filePath);
		WordList wordList = parser.parse(filePath);
		if (argumentCount < 2) {

			// output to standard output
			TextFileWordListWriter writer = new TextFileWordListWriter();
			writer.write(wordList, System.out);
		} else {

			// output to file
			String outputFilePath = args[1];
			WordListFileWriter writer = outputFilePath.toLowerCase().endsWith(
					".dat") ? new DataFileWordListWriter()
					: new TextFileWordListWriter();
			writer.write(wordList, outputFilePath);
		}
	}

	/**
	 * Show usage.
	 */
	private static void showUsage() {
		System.out.println("usage: <filePath> [<outputFilePath>]");
	}

}
